package com.mvcMovie.handler;

import com.mvcMovie.bean.Movie;
import com.mvcMovie.bean.MovieRecord;
import com.mvcMovie.bean.User;
import com.mvcMovie.bean.UserRecord;
import com.mvcMovie.service.MovieService;
import com.mvcMovie.service.RecordService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserHandler {

    @Autowired
    private MovieService movieService;
    @Autowired
    private RecordService recordService;
    @Autowired
    private HttpServletRequest request;

    @GetMapping("/list")
    public String list(Model model){
        List<Movie> movies = movieService.getAllMovie();
        model.addAttribute("movies",movies);

        return "user_list";
    }

    @GetMapping("/look/{id}")
    public String look(
            @PathVariable("id") Integer id,
            Model model){

        Movie movie = movieService.getMovie(id);
        model.addAttribute("movie",movie);

        return "user_look";
    }

    @PostMapping("/record/{movieName}")
    public String saveRecord(
            @PathVariable("movieName") String movieName,
            @RequestParam(value="comment") String comment){

        MovieRecord movieRecord = new MovieRecord(movieName, comment);
        UserRecord userRecord = new UserRecord(getUser().getUserName(),movieName,comment);

        recordService.addUserRecordAndMovieRecord(userRecord,movieRecord);

        return "redirect:/user/list";
    }

    @GetMapping("/record")
    public String UserRecordDetail(Model model){
        List<UserRecord> userRecords = recordService.selectAllRecordByUserName(getUser().getUserName());
        model.addAttribute("userRecords",userRecords);
        return "user_record";
    }
    private User getUser(){
        return (User) request.getSession().getAttribute("user");
    }
}
